/**
 * Copyright (c) 2009.kingbi.
 * All rights reserved.
 */

package com.kingbi.system.function.jsfBean;

import java.sql.SQLException;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.kingbi.system.function.model.FunctionModel;
import com.kingbi.system.function.service.FunctionHelper;
import com.kingbi.system.function.service.FunctionService;

/**
 * Class description goes here.
 * 
 * Created by Auto Code Produce System User: Date: 20091028 Time: 161544
 */
public class FunctionJsfBean extends FunctionDataBean
{
    // 页面导航
    private String outcome;

    // 错误信息提示
    FacesMessage message;

    // //加载service
    FunctionService functionService;

    static Logger logger = Logger.getLogger(FunctionJsfBean.class);

    public void setFunctionService(FunctionService functionService)
    {
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance()
                .getExternalContext().getRequest();
        String searchTag = (String) request.getParameter("searchTag");

        this.functionService = functionService;

        if(searchTag != null && searchTag.equals("isSearch"))
        {
            search();
        }
    }

    /**
     * 页面导航
     * 
     * @return
     */
    public String outcome()
    {
        logger.warn("outcomeoutcome");
        return outcome;
    }

    /**
     * 导向添加页面
     * 
     * @return
     */
    public String preAdd()
    {
        getEmptyJsfBean();
        logger.warn("**********************perAdd()");

        return "addFunction";
    }

    /**
     * 导向修改页面
     * 
     * @return
     */
    public String preUpdate()
    {

        logger.warn("**********************perUpdate()");
        try
        {
            int n = tData.getRowCount();
            for (int i = 0; i < n; i++)
            {
                tData.setRowIndex(i);
                if(selected.isSelected())
                {
                    setChecked(false);
                    FunctionModel tempModel = new FunctionModel();
                    tempModel = (FunctionModel) tData.getRowData();
                    FunctionModel updateModel = new FunctionModel();
                    updateModel = functionService.loadFunction(tempModel.getFunctionID());

                    if(updateModel.getFatherFunCode() != null
                            && !updateModel.getFatherFunCode().equals("")
                            && !updateModel.getFatherFunCode().equals("null")
                            && !updateModel.getFatherFunCode().equals("0"))

                    {
                        FunctionModel fatModel = new FunctionModel();
                        List<FunctionModel> tempList = null;
                        tempList = functionService.loadFunctionByCode(updateModel
                                .getFatherFunCode());
                        updateModel.setFatherName(tempList.get(0).getName());
                    }
                    getJsfDataBean(updateModel);
                }
            }

        }
        catch (Exception e)
        {
            return "failure";
        }
        logger.warn("********************************");
        return "updateFunction";
    }

    /**
     * 提交添加或修改操作
     * 
     * @return
     */
    public String save()
    {
        logger.warn("**********************save()");
        FunctionModel functionModel = new FunctionModel();
        functionModel = super.getJsfModel();
        try
        {
            functionService.saveFunction(functionModel);
            getEmptyJsfBean();
            search();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return "success";
    }

    /**
     * 删除
     * 
     * @return
     */
    public String delete()
    {
        try
        {
            int n = tData.getRowCount();
            for (int i = 0; i < n; i++)
            {
                tData.setRowIndex(i);
                if(selected.isSelected())
                {
                    setChecked(false);
                    FunctionModel tempModel = new FunctionModel();
                    tempModel = (FunctionModel) tData.getRowData();
                    functionService.deleteFunction(tempModel.getFunctionID());
                    selected.setSelected(false);
                }
            }
            getEmptyJsfBean();
            search();
        }
        catch (Exception e)
        {
        	e.printStackTrace();
            return "failure";
        }
        return "success";
    }

    /**
     * 显示详细信息
     * 
     * @return
     */
    public String show()
    {
        try
        {
            FacesContext context = FacesContext.getCurrentInstance();
            String value = (String) context.getExternalContext().getRequestParameterMap().get(
                    "functionID");
            int i_funID = 0;
            if(value != null && !value.equals("") && !value.equals("null"))
            {
                i_funID = Integer.parseInt(value);
            }
            FunctionModel updateModel = new FunctionModel();
            updateModel = functionService.loadFunction(i_funID);
            getJsfDataBean(updateModel);
            return "showFunction";

        }
        catch (Exception e)
        {
            return "failure";
        }

    }

    /**
     * 从其它页面返回到查询列表页面
     * 
     * @return
     */
    public String backToSearch()
    {
        getEmptyJsfBean();
        search();
        return "success";
    }

    /**
     * 查询方法
     * 
     * @return
     */
    public String search()
    {
        tData = null;
        selected = null;
        logger.warn("**********************search()");
        String s_new_CurrentPage = (String) FacesContext.getCurrentInstance().getExternalContext()
                .getRequestParameterMap().get("newCurrentPage");
        String s_query_flag = (String) FacesContext.getCurrentInstance().getExternalContext()
                .getRequestParameterMap().get("queryFlag");

        // 功能管理、浏览权限标识
        String s_funRight = (String) FacesContext.getCurrentInstance().getExternalContext()
                .getRequestParameterMap().get("funRight");
        // 列表页面提交查询标识
        String s_searchFlag = (String) FacesContext.getCurrentInstance().getExternalContext()
                .getRequestParameterMap().get("searchFlag");
        if(s_funRight!=null && !s_funRight.equals("") && !s_funRight.equals("null"))
        {
            setMagFlag(s_funRight);
        }
        

        FunctionModel functionModel = new FunctionModel();
        functionModel = super.getJsfModel();
        if(s_query_flag != null && s_query_flag.equals("ispage"))
        {
            listUpdateFlag = false;
        }
        else
        {
            listUpdateFlag = true;
            if(!(s_searchFlag!=null && s_searchFlag.equals("isListSearch")))
            {
                getEmptyJsfBean();
            }      
        }


        /*
         * 总记录数
         */
        if(listUpdateFlag)
        {
            setRecordCount(functionService.queryCount(functionModel));
        }
        /*
         * 当前页号
         */
        if(s_new_CurrentPage != null && !s_new_CurrentPage.equals("")
                && !s_new_CurrentPage.equals("null"))
        {
            if(!(s_new_CurrentPage.equals("newPage")))
            {
                setCurrentPage(Integer.parseInt(s_new_CurrentPage));
            }
        }
        else
        {
            setCurrentPage(1);
        }
        /*
         * 处理分页
         */
        dealPage(getRecordCount(), getPageRecord(), getCurrentPage());
        /*
         * 根据分页获取数据记录
         */
        try
        {
        	setStartRecordNum(((getCurrentPage() - 1) * getPageRecord() + 1) < 0 ? 0 : (getCurrentPage() - 1) * getPageRecord() + 1);
			setEndRecordNum(getPageRecord() * getCurrentPage());
            setItems(functionService.listFunction(functionModel, (getCurrentPage() - 1)
                    * getPageRecord() + 1, getPageRecord()));
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return "success";
    }

    public void validateFunctionCode(FacesContext context, UIComponent component, Object obj)
            throws ValidatorException
    {
        try
        {
            List<FunctionModel> funList = null;
            funList = functionService.loadFunctionByCode(obj.toString());
            if(funList != null && funList.size() > 0)
            {
                throw new ValidatorException(new FacesMessage("roleCode", "角色编码重复--请重新填写标识"));
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 构造角色添加和修改的功能树
     */
    public String getDtree()
    {
        FunctionHelper funHel = FunctionHelper.getInstance(functionService);
        try
        {
            this.setDtree(funHel.createFunctionTree());
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }

        return super.getDtree();
    }

}
